frappe.ui.form.on("Sales Order", {
    refresh(frm) {
        if (!frm.doc) return;

        const is_submitted = frm.doc.docstatus === 1;
        const is_closed = frm.doc.status === "Closed";
        const is_cancelled = frm.doc.status === "Cancelled";

        // 仅在已提交且未关闭/未取消时显示
        if (!(is_submitted && !is_closed && !is_cancelled)) {
            return;
        }

        // Get Shopify Fulfillments
        frm.add_custom_button(__("Get Shopify Fulfillments"), () => {
            if (!hasShopifyOrderId(frm.doc)) {
                frappe.msgprint(__("This is not a Shopify order; cannot fetch fulfillment info"));
                return;
            }
            frappe.call({
                method: "upsystem.upsystem.api_shop.get_shopify_order_fulfillments",
                args: { sales_order_name: frm.doc.name },
                freeze: true,
                freeze_message: __("Fetching fulfillments…"),
                callback(r) {
                    if (r.message && r.message.success) {
                        // 复用列表脚本中的展示函数（若已加载）
                        if (typeof show_fulfillment_info === 'function') {
                            show_fulfillment_info(r.message.data);
                        } else {
                            // 简要回显
                            frappe.msgprint(__("Fetched {0} fulfillments", [(r.message.data.fulfillments || []).length]));
                        }
                    } else {
                        frappe.msgprint({ title: __("Failed"), message: r.message?.error || __("Unknown error"), indicator: "red" });
                    }
                }
            });
        }, __("Shopify"));

        // Modify Shopify Fulfillment (tracking)
        frm.add_custom_button(__("Modify Shopify Fulfillment"), () => {
            if (!hasShopifyOrderId(frm.doc)) {
                frappe.msgprint(__("This is not a Shopify order; cannot modify fulfillment info"));
                return;
            }

            // 预取缺省值（若全局有 resolveTrackingDetails 则复用）
            let defaults = { tracking_number: '', carrier: 'Flowa', tracking_url: '' };
            try {
                if (typeof resolveTrackingDetails === 'function') {
                    defaults = resolveTrackingDetails(frm.doc) || defaults;
                }
            } catch (e) {}

            const d = new frappe.ui.Dialog({
                title: __("Modify Shopify Fulfillment Info"),
                fields: [
                    { fieldtype: "Data", fieldname: "tracking_number", label: __("Tracking Number"), reqd: 1, default: defaults.tracking_number || '' },
                    { fieldtype: "Data", fieldname: "carrier", label: __("Carrier"), default: defaults.carrier || 'Flowa' },
                    { fieldtype: "Data", fieldname: "tracking_url", label: __("Tracking URL"), default: defaults.tracking_url || '' }
                ],
                primary_action_label: __("Update"),
                primary_action(values) {
                    d.hide();
                    const tn = (values.tracking_number || '').trim();
                    if (!tn) {
                        frappe.msgprint(__("Please enter a tracking number"));
                        return;
                    }
                    frappe.call({
                        method: "upsystem.upsystem.api_shop.update_shopify_fulfillment_tracking",
                        args: {
                            sales_order_name: frm.doc.name,
                            tracking_number: tn,
                            tracking_url: (values.tracking_url || '').trim(),
                            carrier: (values.carrier || '').trim() || 'Flowa'
                        },
                        freeze: true,
                        freeze_message: __("Updating fulfillment…"),
                        callback(r) {
                            if (r.message && r.message.success) {
                                frappe.show_alert({ message: __("Fulfillment info updated"), indicator: "green" });
                                frm.reload_doc();
                            } else {
                                frappe.msgprint({ title: __("Update Failed"), message: r.message?.error || __("Unknown error"), indicator: "red" });
                            }
                        }
                    });
                }
            });
            d.show();
        }, __("Shopify"));

        // Manual Fulfillment (Sync to WDT -> Update Shopify)
        frm.add_custom_button(__("Manual Fulfillment"), () => {
            if (!hasShopifyOrderId(frm.doc)) {
                frappe.msgprint(__("This is not a Shopify order; cannot perform manual fulfillment"));
                return;
            }

            frappe.confirm(
                __("Are you sure to manually fulfill order '{0}'?\n\nThis will:\n1. Sync to WDT\n2. Update Shopify fulfillment info", [frm.doc.name]),
                function () {
                    frappe.show_alert({ message: __("Syncing to WDT…"), indicator: 'blue' });
                    frappe.call({
                        method: "upsystem.upsystem.api.sync_sales_order_to_wdt",
                        args: { sales_order_name: frm.doc.name },
                        callback(res) {
                            if (!(res.message && res.message.success)) {
                                frappe.msgprint(__("WDT sync failed: {0}", [res.message?.message || 'Unknown error']));
                                return;
                            }
                            if (res.message.reserve_info && typeof maybe_show_low_balance_dialog === "function") {
                                maybe_show_low_balance_dialog(res.message.reserve_info);
                            }

                            // 解析跟踪号等
                            let resolved = { tracking_number: '', carrier: 'Flowa', tracking_url: '' };
                            try { if (typeof resolveTrackingDetails === 'function') resolved = resolveTrackingDetails(frm.doc) || resolved; } catch (e) {}
                            const tracking_number = (resolved.tracking_number || '').trim();
                            const tracking_url = (resolved.tracking_url || '').trim();
                            const carrier = (resolved.carrier || 'Flowa').trim();

                            if (!tracking_number) {
                                frappe.msgprint(__("Tracking number not found; please ensure WDT sync produced a tracking number"));
                                return;
                            }

                            // 获取 fulfillment_orders 以执行更新
                            get_fulfillment_orders_for_update_form(frm.doc.name, function(fulfillment_orders) {
                                if (!fulfillment_orders || fulfillment_orders.length === 0) {
                                    frappe.msgprint(__("Unable to get fulfillment orders; please check order status"));
                                    return;
                                }
                                frappe.call({
                                    method: "upsystem.upsystem.api_shop.update_shopify_fulfillment",
                                    args: {
                                        sales_order_name: frm.doc.name,
                                        tracking_number: tracking_number,
                                        fulfillment_orders: fulfillment_orders,
                                        tracking_url: tracking_url,
                                        carrier: carrier
                                    },
                                    freeze: true,
                                    freeze_message: __("Updating Shopify fulfillment…"),
                                    callback(u) {
                                        if (u.message && u.message.success) {
                                            frappe.show_alert({ message: __("Manual fulfillment completed! Tracking number: {0}", [tracking_number]), indicator: 'green' });
                                            frm.reload_doc();
                                        } else {
                                            frappe.msgprint(__("Shopify fulfillment update failed: {0}", [u.message?.error || 'Unknown error']));
                                        }
                                    }
                                });
                            });
                        }
                    });
                }
            );
        }, __("Shopify"));
    }
});

function hasShopifyOrderId(doc) {
    const v = (doc && (doc.custom_shopify_order_id || doc.shopify_order_id)) || '';
    return v && String(v).length >= 10 && v !== '0';
}

function get_fulfillment_orders_for_update_form(sales_order_name, callback) {
    frappe.call({
        method: "upsystem.upsystem.api_shop.get_shopify_order_fulfillments",
        args: { sales_order_name },
        callback: function(response) {
            if (response.message && response.message.success) {
                const fulfillment_orders = [];
                if (response.message.data && response.message.data.fulfillment_orders) {
                    response.message.data.fulfillment_orders.forEach(function(fo) {
                        const line_items = [];
                        if (fo.line_items) {
                            fo.line_items.forEach(function(item) {
                                line_items.push({ id: item.id, quantity: item.remaining_quantity || item.total_quantity || 1 });
                            });
                        }
                        fulfillment_orders.push({ fulfillmentOrderId: fo.id, fulfillmentOrderLineItems: line_items });
                    });
                }
                callback(fulfillment_orders);
            } else {
                frappe.msgprint(__("Failed to get fulfillment order data: {0}", [response.message?.error || 'Unknown error']));
                callback([]);
            }
        }
    });
}
